<?php View::display('accounting/menu');?>
<!-- .head -->
<header class="head">
	<!-- ."main-bar -->
	<div class="main-bar">
		<div class="container-fluid">
			<div class="row-fluid">
				<div class="span12">
					<h3>
						<i class="icon-wrench"></i> การจัดการ Package
					</h3>
				</div>
			</div>
			<!-- /.row-fluid -->
		</div>
		<!-- /.container-fluid -->
	</div>
	<!-- /.main-bar -->
</header>
<!-- /.head -->
<!-- #content -->
<div id="content">
	<!-- .outer -->
	<div class="container-fluid outer">
	
		<div class="row-fluid">
			<!-- .inner -->
			<div class="span12 inner">
				<!--Begin Datatables-->
				<div class="row-fluid">
					<div class="span12">
						<div class="box">
							<header>
								<div class="text-center" style="padding: 10px;"><button class="btn btn-success addButton">Add</button></div>
							</header>
							<div class="body">
								<table class="table table-bordered dataTable responsive">
									<thead>
										<tr>
											<th>id</th>
											<th>type</th>
											<th>name</th>
											<th></th>
											<th></th>
										</tr>
									</thead>
									<tbody>
										<?php
										foreach($params['packages'] as $key => $package){
										$del = "<button class=\"delButton btn btn-danger\" aid=\"{$package['id']}\">ลบ</button>";
										if($package['id'] == 16){
											$del = '';
										}
										echo <<<HTML
											<tr class="package-row" packageId="{$package['id']}">
												<td class="id">{$package['id']}</td>
												<td class="type">{$package['type']}</td>
												<td class="name">{$package['name']}</td>
												<td class="edit"><button class="editButton btn btn-warning" aid={$package['id']}>แก้ไข</button></td>
												<td class="del">{$del}</td>
											</tr>
HTML;
										}?>
									</tbody>
								</table>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<!--Begin Datatables-->
	</div>
</div>
<script type="text/template" class="modalText">
	<div class="modal hide fade">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
			<h3>Edit package id <span class="packageId"></span></h3>
		</div>
		<div class="modal-body">
			<form class="formAccount">
				<label>ชื่อ</label>
				<input type="text" class="name" value="" />
				<label>รายละเอียด</label>
				<textarea type="text" class="info"></textarea>
				<label>ราคา</label>
				<fieldset class="prices-fieldset"></fieldset>
				<button class="btn addPrice">เพิ่มราคา/เดือน</button>
			</form>
		</div>
		<div class="modal-footer">
			<a href="#" class="btn cancel">Cancel</a>
			<a href="#" class="btn btn-primary saveChange">Save changes</a>
		</div>
	</div>
</script>
<script type="text/template" class="modalAdd">
	<div class="modal hide fade">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
			<h3>Edit package id <span class="packageId"></span></h3>
		</div>
		<div class="modal-body">
			<form class="formAccount">
				<label>ประเภท</label>
				<select class="type">
					<option value="colo">colo</option>
					<option value="vps">vps</option>
					<option value="hosting">hosting</option>
				</select>
				<label>ชื่อ</label>
				<input type="text" class="name" value="" />
				<label>รายละเอียด</label>
				<textarea type="text" class="info"></textarea>
				<label>ราคา</label>
				<fieldset class="prices-fieldset"></fieldset>
				<button class="btn addPrice">เพิ่มราคา/เดือน</button>
			</form>
		</div>
		<div class="modal-footer">
			<a href="#" class="btn cancel">Cancel</a>
			<a href="#" class="btn btn-primary Add">Add</a>
		</div>
	</div>
</script>
<script type="text/javascript">
$(function(){

	$('.package-row')
    .delegate('.delButton', 'click', function(event){
        if(!window.confirm('ยืนยันการลบ')){
            return false;
        }
		var dTarget = $(event.delegateTarget);
		var packageId = dTarget.attr('packageId');
		$('.delButton', dTarget).button('loading');
		$.ajax('index.php?page=accounting/package.rest', {
			type: 'DELETE',
			data: {id: packageId},
			dataType: 'JSON',
			success: function(data){
				if(data.success){
                    delRow(dTarget);
                    return false;
				}
                $('.delButton', dTarget).button('reste')
			}
		});
	})
	.delegate('.editButton', 'click', function(event){
		var dTarget = $(event.delegateTarget);
		var target = $(event.target);
		var packageId = dTarget.attr('packageId');

		target.button('loading');
		$.get('index.php', { page: 'accounting/package.rest', id: packageId }, function(data){
			target.button('reset');
			
			var modal = $($('.modalText').html());
			
			$('.packageId', modal).text(data.id);
			$('.name', modal).val(data.name);
			$('.info', modal).val(data.info);
			
			modal.modal();
			modal.on('hidden', function(){
				modal.remove();
			});

			var pricePrototype = $('<p class="price-p"><input type="text" class="input-small price-price" /> บาท / <input type="text" class="input-small price-month" /> เดือน</p>');

			function addPrice(price, month)
			{
				var priceEl = pricePrototype.clone();
				$('.price-price', priceEl).val(price);
				$('.price-month', priceEl).val(month);
				if(month == 1){
					$('.price-month', priceEl).attr('readonly', true);
				}
				$('.prices-fieldset', modal).append(priceEl);
				return priceEl;
			}

			$(data.prices).each(function(index, price){
				addPrice(price.price, price.month);
			});

			$('.addPrice', modal).click(function(event){
				event.preventDefault();
				addPrice('', '');
			});

			$('.saveChange', modal).click(function(){
				var putData = {
						id: data.id,
						name: $('.name', modal).val(),
						info: $('.info', modal).val()
					};
				var prices = [];
				$('.price-p', modal).each(function(index, priceEl){
					if(!($('.price-price', priceEl).val() == '' || $('.price-month', priceEl).val() == ''))
					prices.push({ price: $('.price-price', priceEl).val(), month: $('.price-month', priceEl).val() });
				});
				putData.prices = prices;
                $('.saveChange', modal).button('loading');
				$.ajax('index.php?page=accounting/package.rest', {
					dataType: 'JSON',
					type: 'PUT',
					data: putData,
					success: function(data){
                        $('.saveChange', modal).button('reset');
						if(data.success){
							modal.modal('hide');
							$('.name', dTarget).text(putData.name);
						}
					}
				});
			});
			$('.cancel', modal).click(function(){
				$('.close', modal).click();
			});
		}, 'JSON');
	});

	$('.addButton').click(function(event){
		event.preventDefault();
		var modal = $($('.modalAdd').html());
		
		modal.modal();
		modal.on('hidden', function(){
			modal.remove();
		});

		var pricePrototype = $('<p class="price-p"><input type="text" class="input-small price-price" /> บาท / <input type="text" class="input-small price-month" /> เดือน</p>');
		
		function addPrice(price, month)
		{
			var priceEl = pricePrototype.clone();
			$('.price-price', priceEl).val(price);
			$('.price-month', priceEl).val(month);
			$('.prices-fieldset', modal).append(priceEl);
			return priceEl;
		}
		var firstPrice = addPrice('', '1');
		$('.price-month', firstPrice).attr('readonly', true);

		$('.addPrice', modal).click(function(event){
			event.preventDefault();
			addPrice();
		});

		$('.type', modal).change(function(){
			var val = $(this).val() == 'hosting'? '12': '1';
			$('.price-month', firstPrice).val(val);
		});
		
		$('.Add', modal).click(function(event){
			var sendData = {
					type: $('.type', modal).val(),
					name: $('.name', modal).val(),
					info: $('.info', modal).val(),
					prices: []
				};
			
			$('.price-p', modal).each(function(index, priceEl){
				if(!($('.price-price', priceEl).val() == '' || $('.price-month', priceEl).val() == ''))
				sendData.prices.push({ price: $('.price-price', priceEl).val(), month: $('.price-month', priceEl).val() });
			});
			
			$('.Add', modal).button('loading');
			$.ajax('index.php?page=accounting/package.rest', {
				dataType: 'JSON',
				type: 'POST',
				data: sendData,
				success: function(data){
					if(data.success){
						location.reload();
					}
				}
			});
		});
		$('.cancel', modal).click(function(){
			$('.close', modal).click();
		});
	});

    var oTable = $('.dataTable').dataTable({"bFilter": false, "bInfo": false, "bSort": false,
        sDom: "<'pull-right'l>t<'row-fluid'<'span6'f><'span6'p>>",
        sPaginationType: "bootstrap",
        oLanguage: {
            "sLengthMenu": "Show _MENU_ entries"
        }
    });

    function delRow(row){
        $(row).fadeOut(function(){
            row = $(row).get(0);
            oTable.fnDeleteRow(oTable.fnGetPosition(row));
        });
    }

});
</script>